<template>
  <el-container class="app-container">
    <el-header class="m-t-20">
      <el-button @click="addRoleBtn" type="primary" icon="el-icon-plus">添加角色</el-button>
    </el-header>
    <table-view
      :columns="tableContent"
      :pageList="columnData"
      :templateDiv="{status:true,operation:true}"
    >
      <template slot="status" slot-scope="scope">
        <el-tag :type="scope.row.status?'success':'danger'" size="mini" effect="dark">{{ scope.row.status?'正常':'停用' }}
        </el-tag>
      </template>
      <template slot="operation" slot-scope="scope">
        <el-row class="tx-l">
<!--          <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'menuManage')">权限管理</el-button>-->
          <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'update')">编辑</el-button>
          <el-button size="mini" type="danger" @click="editBtnClick(scope.row ,'delete')">删除</el-button>
        </el-row>
      </template>
    </table-view>
    <!--分页-->
    <pagination-view :pagesize="pageInfo.pageSize"
                     :currentPage="pageInfo.pageNumber"
                     :total="total"
                     @size-change="sizeChange"
                     @current-change="pageChange"
    ></pagination-view>
    <!--添加角色-->
    <el-dialog :title="showtitle" :visible.sync="addfreightdialog" width="56%" center>
      <el-form ref="form" :model="form" label-width="100px" :rules="formRules" style="width: 60%">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model.trim="form.roleName" placeholder="请输入角色名称" class="rolemanage-input" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色说明：" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="角色状态：" prop="status">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFreightForm('addFeightForm')">确 定</el-button>
          <el-button @click="resetFreightForm()">取 消</el-button>
        </span>
    </el-dialog>

    <!--权限管理-->
    <el-dialog title="权限管理" :visible.sync="dialogMenu" width="56%" center>
      <el-form ref="formMenu" :model="formMenu" label-width="100px" style="width: 60%">
        <el-form-item label="角色名称:" prop="roleName">
          {{formMenu.roleName}}
        </el-form-item>

        <el-form-item label="权限:">
          <el-tree
            style="width: 300px"
            class="rolemanage-tree"
            :data="authoritydata"
            show-checkbox
            node-key="menuId"
            ref="tree"
            highlight-pageNum
            :props="defaultProps"
            :default-checked-keys="defaultcheckkeys"
          ></el-tree>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitMenuForm">确 定</el-button>
          <el-button @click="dialogMenu=true">取 消</el-button>
        </span>
    </el-dialog>
  </el-container>
</template>

<script>
  import TableView from "@/components/TableView";
  import PaginationView from "@/components/PaginationView";
  import * as roleManage from "@/api/main/account/roleManage";
  import resData from './res'

  export default {
    name: 'roleManage',
    components: {
      PaginationView,
      TableView
    },
    data() {
      return {
        dialogMenu: false,
        formMenu: {
          roleName: ''
        },
        tableContent: [{
          field: "roleName",
          label: '角色名称',
        }, {
          field: "remark",
          label: '角色说明',
        }, {
          field: "createdTime",
          label: '创建时间',
        }, {
          field: "currentUserNum",
          label: '当前人数',
        }, {
          field: "status",
          label: '状态',
        }, {
          field: "operation",
          label: '操作',
          width: 200
        }],
        customWidth: "",
        columnData: [],
        total: null,
        pageInfo: {
          pageNum: 1,
          pageSize: 20,
          roleName: '',
        },
        showtitle: "添加角色",
        showType: 'add',
        addfreightdialog: false,
        form: {
          roleName: "",
          hasAllPerm: 1,
          remark: '',
          status: true,
          project: 'B'
        },
        role_id: 0,
        formRules: {
          roleName: [{
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
            {
              min: 1,
              max: 10,
              message: '最多10个字符',
              trigger: 'blur'
            },
          ],
          status: [{required: true, message: '必填'}]
        },
        getcheckedkeys: [], //获取勾选的数据
        defaultcheckkeys: [], //默认勾选
        authoritydata: [],
        defaultProps: {
          children: "children",
          label: "name"
        }
      };
    },

    methods: {
      //搜索
      searchList() {
        this.getData()
      },
      //重置搜索
      resetForm() {
        this.pageInfo = {
          pageNum: 1,
          pageSize: 20,
          roleName: '',
        }
        this.getData()
      },
      getData() {
        roleManage.getRoleList(this.pageInfo).then(res => {

          this.columnData = res.body.records
          this.total = Number(res.body.total) || 0
        });
      },
      //获取树状菜单
      getPrivilegeList() {
        // this.authoritydata = resData.body
        roleManage.getPrivilegeList().then(res => {
          this.authoritydata = res.body

        })
      },
      setGridDataFromTree(list, dataSource) {
        if (!(Array.isArray(dataSource) && dataSource.length > 0))
          return;
        dataSource.forEach((father) => {
          list.push(father);
          if (typeof (father.children) == "undefined") {
          } else {
            this.setGridDataFromTree(list, father.children);
          }
        });
        return list
      },

      submitMenuForm() {
        // _this.getCheckedKeys();
        let getCheckedKeys = this.$refs.tree.getCheckedKeys()
        if (getCheckedKeys < 1) {
          this.$message.error('未分配权限！');
          return
        }
        roleManage.updateMenu(this.formMenu.id, {menuId: getCheckedKeys}).then(res => {
          this.handleMessage(res)
          if(res.code === '200')this.dialogMenu = false
        })
      },


      createRole(data) {
        roleManage.createRole(data).then(res => {
          this.handleMessage(res)
          if (res.code === '200') {
            this.resetFreightForm();
            this.getData();
          }
        });
      },
      updateRole(data) {
        roleManage.updateRole(data.id, data).then(res => {
          this.handleMessage(res)
          if (res.code === '200') {
            this.resetFreightForm();
            this.getData();
          }
        });
      },
      deleteRole(id) {
        roleManage.deleteRole(id).then(res => {
          this.handleMessage(res)
          if (res.code === '200') {
            this.getData();
          }
        });
      },
      editBtnClick(val, type) {
        let _this = this;
        switch (type) {
          case "update":
            _this.showtitle = "编辑角色";
            _this.showType = 'edit';
            _this.getRoleInfo(val.id);
            break;
          case "delete":
            this.$confirm(`确定删除吗？是否继续?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              _this.deleteRole(val.id);
              _this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })
            break;
          case 'menuManage':
            _this.formMenu = val
            _this.dialogMenu = true
            _this.defaultcheckkeys = []
            _this.$nextTick(() => {
              _this.$refs.tree.setCheckedKeys([], true)
            })
            break
        }
      },
      getRoleInfo(id) {
        this.role_id = id
        this.addfreightdialog = true;
        roleManage.getRoleInfo(id).then(res => {
          this.form = res.body
        }).then(() => {

          // roleManage.getMenusListByid(id).then(resData => {
          let data = resData.body
          let newArr = []
          newArr = this.setGridDataFromTree([], data, "").filter(item => item.isIfView == 0)
          newArr.forEach(value => {
            this.$refs.tree.setChecked(value, true, false);
          });
          // })
        })
      },
      addRoleBtn() {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.form = {
          roleName: "",
          hasAllPerm: 1,
          remark: '',
          status: true,
          project: 'B'
        },
          this.addfreightdialog = true;
        this.showType = 'add';
        this.showtitle = "添加角色";
      },
      getCheckedKeys(callback) {
        let _getcheckedkeys = []
        let _data = this.$refs.tree.getCheckedKeys()
        _data.map((item, index) => {
          if (item !== undefined) {
            _getcheckedkeys.push(item)
          }
        })
        this.getcheckedkeys = _getcheckedkeys
      },
      submitFreightForm(formName) {
        let _this = this
        _this.$refs.form.validate((valid) => {
          if (valid) {
            let _type = _this.editclickindex == -1 ? 'add' : 'edit'
            debugger
            if (this.showType === 'add') {
              _this.createRole(_postdata, _type)
            } else {
              _this.updateRole(_postdata, _type)
            }
          }
        })
      },
      resetFreightForm() {
        this.$refs.form.resetFields();
        this.addfreightdialog = false;
      },
      // pageSize变化函数
      sizeChange(val) {
        this.pageInfo.pageSize = val;
        this.getData();
      },
      // page变化函数
      pageChange(val) {
        this.pageInfo.pageNumber = val;
        this.getData();
      }
    },
    computed: {
      //...mapGetters(["tableContent"])
    },
    created: function () {
      this.getData();
      this.getPrivilegeList()
    }
  };
</script>
<style lang="scss">
  .rolemanage {
    padding: 20px;

    .add-more {
      form {
        margin: 0 0 0 10%;

        .rolemanage-tree {
          margin: 10px;
        }
      }

      .rolemanage-input {
        width: 195px;
      }
    }
  }
</style>

